package crawler.extension.ocr.service;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;

import crawler.extension.ocr.tool.PathTool;
import crawler.utility.http.HttpClientUtil;
import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;

@Service
public class OCRService {

	private static Logger log = LoggerFactory.getLogger(OCRService.class);

	@Autowired
	private PathTool pathTool;

	public String getOCR(String fileName, String website, String contrast) {
		log.info("fileName : " + fileName + " website : " + website+ " contrast : " + contrast);

		JSONObject resultObj = new JSONObject();
		
		String result = ocr(fileName, website);
		resultObj.put("text", result);
		
		if (contrast != null) {
			resultObj.put("contains", result.contains(contrast));
		}
		
		return resultObj.toJSONString();
	}
	
	
	public String getOCR(String fileName, String website) {
		return getOCR(fileName, website, null);
	}

	
	public String fetchPic(String url, String website) {
		log.info("url : " + url + "website : " + website);

		String result = null;
		
		Map<String, String> configMap = pathTool.selectConfig(website);
		
		String path = configMap.get("filePath") + System.currentTimeMillis() + ".jpg";
		
		HttpClientUtil httpClientUtil = new HttpClientUtil();
		httpClientUtil.setUrl(url);
		httpClientUtil.setPathName(path);

		try {
			httpClientUtil.downloadFile();
		} catch (IOException e1) {
			e1.printStackTrace();
			log.error("HTTP Fail", e1);
			return result;
		}

		return path;
	}
	

	private String ocr(String fileName, String website) {

		String result = "";

		Map<String, String> configMap = pathTool.selectConfig(website);

		String path = configMap.get("filePath") + fileName;

		File imageFile = new File(path);
		ITesseract instance = new Tesseract();

		String tessdataPath = configMap.get("tessdata");
		log.info("tessdata path : " + tessdataPath);

		instance.setDatapath(tessdataPath);
		instance.setLanguage("num+eng+chi_sim");

		try {

			result = instance.doOCR(imageFile);
			log.info("OCR result : " + result);
			System.out.println(result);

			System.out.println(result.contains("1 2 3\n4 5 6\n7 8 9\n0"));
		} catch (TesseractException e) {
			e.printStackTrace();
			log.error("OCR Fail", e);
		}
		return result;
	}

	
}
